<template>
  <div class="furniture">
    <el-button
      @click="handeAdd"
      type="success"
      style="margin-bottom: 10px; background-color: #9e83f8; border: 0"
      >添加产品</el-button
    >
    <el-table
      :data="filterTableData"
      style="width: 100%"
      :highlight-current-row="true"
      border
    >
      <el-table-column type="index" prop="id" label="编号" width="55" />
      <el-table-column prop="createdAt" label="产品" width="150px">
        <template #default="scope">
          <!-- preview-teleported="true"  解决图片放大功能的 -->
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="urlPush(scope.row.url)"
              :zoom-rate="1.2"
              :preview-src-list="scope.row.srcList"
              :initial-index="999"
              :preview-teleported="true"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="名称"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            class="mt-2"
            inline-prompt
            :active-icon="Check"
            :inactive-icon="Close"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="addedTime"
        label="产品编号"
        width="150"
        class="addedTime"
        show-overflow-tooltip
      />
      <el-table-column
        prop="productSize"
        label="产品大小"
        width="200"
        class="productSize"
        show-overflow-tooltip
      />
      <el-table-column prop="releaseTime" label="上架时间" width="200" />
      <el-table-column prop="price" label="价格">
        <template #default="scope">
          <span>{{ scope.row.price }} 元</span>
        </template>
      </el-table-column>
      <el-table-column prop="surplus" label="余货" width="200">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.surplus"
            :min="0"
            :disabled="true"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="200">
        <template #header>
          <el-input
            v-model="search"
            size="small"
            placeholder="查询产品"
            style="height: 5vh; font-size: 16px"
          />
        </template>
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleRevise(scope.row)"
            >修改</el-button
          >
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            >下架</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 删除确认框 -->
  <el-dialog v-model="dialogVisible" title="提示" width="30%">
    <span>是否下架此产品</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handrevess"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 添加弹出框 -->
  <el-dialog v-model="addProductDialogVisible" title="添加产品" width="40%">
    <div>
      <el-form :model="newProduct">
        <el-form-item label="产品">
          <el-input v-model="newProduct.name" placeholder="请输入产品" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="newProduct.status" placeholder="请输入状态" />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="newProduct.addedTime"
            placeholder="请输入产品编号"
          />
        </el-form-item>
        <el-form-item label="产品大小">
          <el-input
            v-model="newProduct.productSize"
            placeholder="请输入产品大小"
          />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker
            v-model="newProduct.releaseTime"
            type="date"
            label="Pick a date"
            placeholder="上架时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <!-- <el-input v-model="newProduct.url" placeholder="请撒谎那个穿" /> -->
          <!-- action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :on-success="handleAvatarSuccess" -->
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChange"
            :before-upload="beforeAvatarUpload"
            v-model:file-list="fileList"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="newProduct.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="余货">
          <el-input-number
            v-model="newProduct.surplus"
            :min="0"
            placeholder="请输入余货"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addProductDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addProduct">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 修改框 -->
  <el-dialog v-model="dialogFormVisible" title="修改产品" width="40%">
    <div>
      <el-form :model="reviseProduct">
        <el-form-item label="名称">
          <el-input v-model="reviseProduct.name" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="reviseProduct.status" />
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input v-model="reviseProduct.addedTime" />
        </el-form-item>
        <el-form-item label="产品大小">
          <el-input v-model="reviseProduct.productSize" />
        </el-form-item>
        <el-form-item label="上架时间">
          <el-date-picker
            v-model="reviseProduct.releaseTime"
            type="date"
            label="Pick a date"
            placeholder="上架时间"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="图片URL">
          <el-input v-model="reviseProduct.url" clearable />
        </el-form-item>
        <el-form-item label="余货">
          <el-input-number v-model="reviseProduct.surplus" :min="0" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="reviseProduct.price" placeholder="请输入价格" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, computed, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import type { UploadProps } from "element-plus";

import { Check, Close } from "@element-plus/icons-vue";
import { inquire, addingGoods } from "../../api/shoppin";
import useUserStore from "../../store/modules/user";

const formele: any = ref("");
const fileList: any = "";

// 图片地址
const imageUrl = ref("");

const handleChange: UploadProps['onChange'] = (uploadFile:any) => {
 if (uploadFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
  }else {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!);
    formData.file = uploadFile.raw;
  }
}

// 图片上传前的判断
const beforeAvatarUpload: UploadProps["beforeUpload"] = (uploadFile) => {
  // console.log('before');
  if (uploadFile.type !== "image/jpeg" && uploadFile.type !== "image/png") {
    ElMessage.error("图片必须是jpg或png格式!");
  } else if (uploadFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2MB!");
  } else {
    formData.file = uploadFile;
  }
  return false;
};

// 前缀
const userStore = useUserStore();
const urlHeader = userStore.getHostHead;
console.log(urlHeader);

const urlPush = (str: string) => {
  console.log("str: " + str);

  return urlHeader + str;
  // return str
};
// 添加
const addProductDialogVisible = ref(false);
const newProduct: any = ref<Partial<TableData>>({});
//添加参数
const formData: any = reactive({
  name: "",
  status: "",
  // goods: "",
  surplus: "",
  file: null,
  price: "",
});
// 删除
const dialogVisible = ref(false);
// 查询
const search = ref("");
const price: any = ref(null);

// 修改
const reviseProduct = ref<any>();
const dialogFormVisible = ref(false);
interface TableData {
  id: string;
  name: string;
  status: boolean;
  addedTime: string;
  productSize: string;
  releaseTime: string;
  url: any;
  srcList: Array<any>;
  surplus: number;
  price: number;
}
const tableData = ref<any>([{}]);
// 获取后端数据
const loadData = async () => {
  const result: any = await inquire();
  console.log("商品数据", result.records);
  tableData.value = result.records;
};
loadData();

// 查询
const filterTableData = computed(() =>
  tableData.value.filter(
    (data: any) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
);

// 修改
const handleRevise = (row: TableData) => {
  console.log("修改");
  reviseProduct.value = row;
  dialogFormVisible.value = true;
};
const handleSave = () => {
  // 遍历原始数据，找到与当前行数据相同的数据，并将其替换为修改后的数据
  for (let i = 0; i < tableData.value.length; i++) {
    if (tableData.value[i].id === reviseProduct.value.id) {
      tableData.value[i] = reviseProduct.value;
      break;
    }
  }
  dialogFormVisible.value = false;
};
const delateId = ref("1234");
const handleDelete = (row: any) => {
  console.log("删除", row);
  delateId.value = row.id;
  dialogVisible.value = true;
};
// 删除逻辑
const handrevess = () => {
  tableData.value = tableData.value.filter(
    (item: any) => item.id !== delateId.value
  );
  console.log(tableData.value);

  dialogVisible.value = false;
};

// 添加
const handeAdd = async () => {
  addProductDialogVisible.value = true;
};
const addProduct = async () => {
  if (newProduct.value.name) {
    ElMessage.success("添加成功");
  addProductDialogVisible.value = false
    const product: any = {
      id: (tableData.value.length + 1).toString(),
      ...newProduct.value,
      srcList: [newProduct.value.url],
    };

    let fd = new FormData();
    for (let n in formData) {
      if (n === "file") {
        fd.append("goods", formData.file);
      } else if (n === "status") {
        let sta: any = !!newProduct.value.status ? 1 : 0;
        fd.append("status", sta);
      } else {
        fd.append(n, newProduct.value[n]);
      }
    }
    console.log(999, fd);

    const request: any = await addingGoods(fd);
    console.log(request);
    if (request.code < 200) {
      tableData.value.push(product);
      newProduct.value = {};
      addProductDialogVisible.value = false;
      console.log("添加了", product);
    } else {
    }
  } else {
    ElMessage.error("请填写必要的产品信息");
  }
};
// 复杂查询
const size = ref<"default" | "large" | "small">("default");
const list: any = ref({
  name: "",
  price: "",
});
</script>

<style scoped >
:deep(.el-table__cell) {
  text-align: center;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

/* .el-table .cell{
  text-align: center !important;
} */

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>